package cn.zl.api.impl.streamproxy;

import cn.zl.api.dto.streamproxy.PlayStreamProxyApiInDTO;
import cn.zl.api.dto.streamproxy.PlayStreamProxyApiOutDTO;
import cn.zl.api.inter.streamproxy.IStreamProxyApiService;
import cn.yunbamboos.id.SnowflakeIdGenerator;
import cn.yunbamboos.mybatis.conditions.Conditions;
import cn.yunbamboos.rest.service.anno.RestServiceMapping;
import cn.yunbamboos.rest.service.dto.out.BaseOutDTO;
import cn.yunbamboos.rest.service.transaction.Transaction;
import cn.zl.config.ZLConfig;
import cn.zl.model.StreamProxy;
import cn.zl.web.impl.StreamService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.time.LocalDateTime;

@Service("StreamProxyApiServiceImpl")
public class StreamProxyApiServiceImpl extends StreamService implements IStreamProxyApiService {

    @Resource
    private SnowflakeIdGenerator snowflakeIdGenerator;
    @Resource
    private ZLConfig zlConfig;

    @RestServiceMapping(url = "/api/stream-proxy/play", name = "播放拉流信息API服务", in = PlayStreamProxyApiInDTO.class, out = PlayStreamProxyApiOutDTO.class, transaction = Transaction.WRITE)
    @Override
    public BaseOutDTO play(PlayStreamProxyApiInDTO in) {
        String realUrl = in.getSession("real_url");
        URI url = URI.create(realUrl);
        String host = url.getHost();
        PlayStreamProxyApiOutDTO out = new PlayStreamProxyApiOutDTO();
        StreamProxy streamProxy = streamProxyMapper.queryForObject(Conditions.create("app", in.getApp()).add("stream", in.getStream())).orElseGet(() -> {
            LocalDateTime now = LocalDateTime.now();
            StreamProxy proxy = new StreamProxy();
            proxy.setProxyId(snowflakeIdGenerator.nextIdStr());
            proxy.setApp(in.getApp());
            proxy.setStream(in.getStream());
            proxy.setUrl(in.getUrl());
            proxy.setRetryCount(-1);
            proxy.setRtpType(0);
            proxy.setTimeoutSec(60);
            proxy.setEnableAudio(false);
            proxy.setAutoClose(true);
            proxy.setState(0);
            proxy.setUpdateTime(now);
            proxy.setCreateTime(now);
            streamProxyMapper.insert(proxy);
            return proxy;
        });
        out.setHost(host);
        out.setApp(streamProxy.getApp());
        out.setStream(streamProxy.getStream());
        out.setConfig(zlConfig);
        return out;
    }

}
